<?php

use Phphub\Core\CreatorListener;

class EvaluationsController extends \BaseController implements CreatorListener
{
    public function __construct()
    {
        parent::__construct();
        $this->beforeFilter('auth');
    }

    public function authorOrAdminPermissioinRequire($author_id)
    {
        if (! Entrust::can('manage_evaluations') && $author_id != Auth::id()) {
            throw new ManageEvaluationsException("permission-required");
        }
    }

    public function store()
    {
        return App::make('Phphub\Creators\EvaluationCreator')->create($this, Input::except('_token'));
    }

    public function vote($id)
    {
        $evaluation = Evaluation::find($id);
        App::make('Phphub\Vote\Voter')->evaluationUpVote($evaluation);
        return Redirect::route('labs.evaluations', ['lab_id' => $evaluation->lab_id]);
    }

    public function destroy($id)
    {
        $evaluation = Evaluation::findOrFail($id);
        $this->authorOrAdminPermissioinRequire($evaluation->user_id);
        $evaluation->delete();

        $evaluation->lab->decrement('evaluation_count', 1);

        Flash::success(lang('Operation succeeded.'));

        return Redirect::route('labs.evaluations', $evaluation->lab_id);
    }

    /**
     * ----------------------------------------
     * CreatorListener Delegate
     * ----------------------------------------
     */

    public function creatorFailed($errors)
    {
        Flash::error(lang('Operation failed.'));
        return Redirect::back();
    }

    public function creatorSucceed($evaluation)
    {
        Flash::success(lang('Operation succeeded.'));
        return Redirect::route('labs.evaluations', ['lab_id' => $evaluation->lab_id]);
    }
}
